//
//  YAYITagGroupViewController.m
//  yayi-医生版
//
//  Created by Veer on 16/4/28.
//  Copyright © 2016年 Veer. All rights reserved.
//

#import "YAYITagGroupViewController.h"
#import "YAYIEditTagGroupViewController.h"

#import "YAYITagGroupNewCell.h"
#import "YAYITagGroupCell.h"
#import "YAYITagGroupItem.h"



@interface YAYITagGroupViewController () <YAYIEditTagGroupViewControllerDelegate>

@property (nonatomic, weak) UIView *noDataFlagView;

@property (nonatomic, strong) NSMutableArray *tagArray;

@end

@implementation YAYITagGroupViewController


- (NSMutableArray *)tagArray
{
    if (nil == _tagArray) {
        _tagArray = [NSMutableArray array];
    }
    return _tagArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    self.title = @"标签";
    
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
//    [self createDataSource];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self createDataSource];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  没有数据时显示
 */
- (void)showNoDataFlag:(BOOL)isHavaData
{
    if (isHavaData) {
        if (self.noDataFlagView) {
            self.noDataFlagView.hidden = YES;
        }
    }else{
        if (self.noDataFlagView) {
            self.noDataFlagView.hidden = NO;
            return;
        }
        
        UIView *noDataFlagView = [[UIView alloc] initWithFrame:self.view.bounds];
        [self.view addSubview:noDataFlagView];
        self.noDataFlagView = noDataFlagView;
        
        UILabel *titleLbl1 = [[UILabel alloc] init];
        titleLbl1.text = @"暂无标签分组";
        titleLbl1.font = [UIFont systemFontOfSize:17];
        titleLbl1.textColor = YAYIColor(107, 178, 242);
        titleLbl1.textAlignment = NSTextAlignmentCenter;
        [noDataFlagView addSubview:titleLbl1];
        [titleLbl1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(@(100 + 64));
            make.centerX.equalTo(noDataFlagView);
        }];
        
        UILabel *titleLbl2 = [[UILabel alloc] init];
        titleLbl2.text = @"通过标签分组你可方便查找和管理您的病人";
        titleLbl2.font = [UIFont systemFontOfSize:15];
        titleLbl2.textColor = YAYIColor(107, 178, 242);
        titleLbl2.textAlignment = NSTextAlignmentCenter;
        [noDataFlagView addSubview:titleLbl2];
        [titleLbl2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(titleLbl1.mas_bottom).offset(5);
            make.centerX.equalTo(noDataFlagView);
        }];
        
        // btn
        UIButton *newBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        newBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [newBtn setTitle:@"新建标签" forState:UIControlStateNormal];
        [newBtn setBackgroundImage:[UIImage imageNamed:@"button_normal"] forState:UIControlStateNormal];
        [noDataFlagView addSubview:newBtn];
        [newBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(titleLbl2.mas_bottom).offset(100);
            make.left.equalTo(@20);
            make.right.equalTo(@-20);
            make.height.equalTo(@40);
        }];
        [newBtn addTarget:self action:@selector(newTagAction:) forControlEvents:UIControlEventTouchUpInside];
        
    }
}


#pragma mark - 获取数据
- (void)createDataSource
{
    // 显示hud
    [SVProgressHUD show];
    
    [self.tagArray removeAllObjects];
    
    [YAYINetWorking getWithURL:patienListTag_url param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
            }else{
                
                NSArray *data = dict[@"data"];
                
                for (NSDictionary *obj in data) {
                    YAYITagGroupItem *item = [YAYITagGroupItem new];
                    [item setValuesForKeysWithDictionary:obj];
                    
                    [self.tagArray addObject:item];
                    YAYILog(@"item.clientcount:%ld", item.clientcount);
                }
                
                
                [self.tableView reloadData];
            }
            
            
            if (0 == self.tagArray.count) {
                [self showNoDataFlag:NO];

            }else{
                [self showNoDataFlag:YES];
            }
        }else{
            
            NSDictionary *erroDict = [NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:nil];
            YAYILog(@"erro:%@", erroDict);
        }
        
        // 取消显示hud
        [SVProgressHUD dismiss];
    }];
    
}



#pragma mark - 点击事件
- (void)newTagAction:(UIButton *)sender
{
    YAYIEditTagGroupViewController *editVc = [[YAYIEditTagGroupViewController alloc] init];
    editVc.addMenberType = YAYIAddMemberTypeNew;
    [self.navigationController pushViewController:editVc animated:YES];
}


#pragma mark - 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (0 == self.tagArray.count) {
        return 0;
    }
    return self.tagArray.count + 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.row) {
        return 44;
    }
    
    return 58;
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (0 == indexPath.row) {
        YAYITagGroupNewCell *cell = [YAYITagGroupNewCell cellWith:tableView];
        return cell;
        
    }
    YAYITagGroupItem *model = self.tagArray[indexPath.row - 1];
    
    YAYITagGroupCell *cell = [YAYITagGroupCell cellWith:tableView];
    cell.item = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    YAYIEditTagGroupViewController *editVc = [[YAYIEditTagGroupViewController alloc] init];

    if (0 != indexPath.row) {
        YAYITagGroupItem *model = self.tagArray[indexPath.row - 1];
        editVc.tagID = [NSString stringWithFormat:@"%ld", model.tagid];
        editVc.tagName = model.tagname;
    }else{
        editVc.addMenberType = YAYIAddMemberTypeNew;
        editVc.delegate = self;
    }
    
    [self.navigationController pushViewController:editVc animated:YES];
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.row) {
        return YES;
    }
    
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (UITableViewCellEditingStyleDelete == editingStyle) {
        YAYILog(@"点击了删除");
        
        YAYITagGroupItem *model = self.tagArray[indexPath.row - 1];
        // 删除标签
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"tagid"] = [NSString stringWithFormat:@"%ld", model.tagid];
        
        YAYILog(@"param:%@", param);
        
        [YAYINetWorking postJsonSerilizeWithURL:patienDelTag_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
            if (error == nil) {
                YAYILog(@"保存标签：%@", dict);
                
                if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                    [SVProgressHUD showWithStatus:@"保存失败"];
                    
                }else{
                    [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                    [self.tagArray removeObjectAtIndex:indexPath.row - 1];
                    
                    if (self.tagArray.count == 0) {
                        
                        [tableView reloadData];
                        [self showNoDataFlag:NO];
                    }else{
                        
                        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                    }
                }
            }else{
                NSString *message = responseError[@"message"];
                [SVProgressHUD showErrorWithStatus:message];
            }
        }];
    }
}


#pragma mark YAYIEditTagGroupViewControllerDelegate
- (void)editTagGroupHaveAddTag
{
    [self createDataSource];
}


@end
